package edu.wtbu.cs.androiddemo.activity.store;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import edu.wtbu.cs.androiddemo.R;


/**
 *
 * todo 读取USB设备中的数据
 */
public class SDStoreSampleActivity extends AppCompatActivity {

    static final String logTag = SDStoreSampleActivity.class.getName();

    private EditText editText;
    private TextView textView;
    private Button buttonSave;
    private Button buttonRead;
    private String fileName = "sdtext.txt";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sdstore_sample);

        initView();
    }

    private void initView() {
        editText = (EditText) findViewById(R.id.edit_content);
        textView = (TextView) findViewById(R.id.tv_content);
        buttonSave = (Button) findViewById(R.id.btn_save);
        buttonRead = (Button) findViewById(R.id.btn_read);
        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    if (ContextCompat.checkSelfPermission(SDStoreSampleActivity.this, Manifest.permission
                            .WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(SDStoreSampleActivity.this, new
                                String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
                    } else {
                        writeToSD();
                    }
                }
            }
        });

        buttonRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    if (ContextCompat.checkSelfPermission(SDStoreSampleActivity.this, Manifest.permission
                            .READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(SDStoreSampleActivity.this, new
                                String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                    } else {
                        readFromSD();
                    }
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (permissions[i].equals("android.permission.READ_EXTERNAL_STORAGE")
                        && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    readFromSD();
                } else {
                    Toast.makeText(this, "拒绝授权", Toast.LENGTH_SHORT).show();
                }
            }
        }
        if (requestCode == 2) {
            for (int i = 0; i < permissions.length; i++) {
                if (permissions[i].equals("android.permission.WRITE_EXTERNAL_STORAGE")
                        && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    writeToSD();
                } else {
                    Toast.makeText(this, "拒绝授权", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    /**
     *
     * todo 模拟器中获取的SDPath有点问题
     */
    private void readFromSD() {
        File SDPath = Environment.getExternalStorageDirectory();
        File file = new File(SDPath, fileName);
        checkFileExist(file);
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
            String content = reader.readLine();
            textView.setText(content);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void writeToSD() {
        String content = editText.getText().toString();
        File SDPath = Environment.getExternalStorageDirectory();
        try {
            String path= SDPath.getPath();
            //file.exists():false file.getAbsolutePath():/storage/emulated/0/sdtext.txt
            Log.i(logTag,path);
            File file = new File(path, fileName);
            checkFileExist(file);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(content.getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkFileExist(File file){
        Log.d("Tag", "file.exists():" + file.exists() + " file.getAbsolutePath():"+ file.getAbsolutePath());

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}